<template>
  <div class="apply-dialog">
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div slot="title" class="flex flex-row align-center justify-content-end">
        <div class="btn-list flex flex-row align-center">
          <el-button
            v-if="workOrdeInfo.status != 0"
            type="warning"
            size="mini"
            :disabled="draftDisabled"
            @click="draftAction(processStructureValue.edges[0])"
          >
            暂存
          </el-button>

          <el-button
            v-if="workOrdeInfo.id > 0 && workOrdeInfo.status == 0"
            type="warning"
            size="mini"
            :disabled="recallDisabled"
            @click="recallOrder()"
          >
            撤回
          </el-button>
          <el-button
            v-for="(item, index) in processStructureValue.edges"
            v-show="item.source === processStructureValue.nodes[active].id &&
              workOrdeInfo.status != 0
            "
            :key="index"
            type="primary"
            size="mini"
            :disabled="submitDisabled"
            @click="submitAction(item)"
          >
            {{ item.label }}
          </el-button>
          <el-button type="primary" size="mini" @click="handlePrint(printData)">
            导出PDF
          </el-button>

          <div class="pl15 pr15">
            上报人：<span class="primary-color">{{ name }}</span>
          </div>
          <div class="pl15 pr15">
            最新状态：<span v-if="recallStatus == 0" class="primary-color">{{
              orderState
            }}</span>
            <span v-else class="danger-color">已撤回申请</span>
          </div>
          <div class="ml50" @click="handleClose">
            <i class="el-icon-close cursor-p font22 line-height-32" />
          </div>
        </div>
      </div>

      <div class="flex flex-row pl30 pr30">

        <div class="baqsj-container flex-auto">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="mb5" />

          <div v-if="dialogVisible" id="printFrom" class="text item">
            <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
              <el-card
                v-show="currentNode.hideTpls === undefined ||
                  currentNode.hideTpls === null ||
                  currentNode.hideTpls.indexOf(tplItem.id) === -1
                "
                :key="tplIndex"
                class="box-card apply-box mt10 mb20"
              >
                <div slot="header" class="clearfix flex flex-row align-center">
                  <div class="line" />
                  <span class="font18 ml10 flex-auto">{{ tplItem.name }}</span>

                </div>
                <fm-generate-form
                  :ref="'generateForm-' + tplItem.id"
                  :preview="currentNode.hideTpls === undefined ||
                    currentNode.hideTpls === null ||
                    currentNode.hideTpls.indexOf(tplItem.id) === -1
                    ? false
                    : true
                  "
                  :remote="remoteFunc"
                  :data="tplItem.form_structure"
                  :disabled="currentNode.readonlyTpls === undefined ||
                    currentNode.readonlyTpls === null ||
                    currentNode.readonlyTpls.indexOf(tplItem.id) === -1
                    ? null
                    : true
                  "
                />
              </el-card>
            </template>
          </div>

        </div>
      </div>
    </el-dialog>
    <LeaderDialog ref="leaderRef" @selectLeader="selectLeader" />

  </div>
</template>

<script>
import Vue from 'vue'
import { GenerateForm } from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import LeaderDialog from './leader/index.vue'

import {
  processStructure,
  createWorkOrder,
  updateWorkOrder,
  draftWorkOrder,
  recallWorkOrder
} from '@/api/xjs/work-order'
import { listAllUser } from '@/api/system/sysuser'
import { getOrdinaryDeptList } from '@/api/system/dept'
import { mapGetters } from 'vuex'
import printJS from 'print-js'
export default {
  name: 'ApplyDialog',
  components: {
    LeaderDialog
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      processKey: '',
      searchPriceNo: '',
      recallStatus: 0,
      printData: {
        printable: 'printFrom',
        header: '',
        ignore: ['no-print']
      },
      workOrdeInfo: {
        id: null,
        status: 1
      },
      limitTechList: [],
      selectLimitData: [],
      loading: false,
      dialogVisible: false,
      limitTechVisible: false,
      submitDisabled: false,
      draftDisabled: false,
      recallDisabled: false,
      downloadVisible: false,
      active: 0,
      total: 0,
      processStructureValue: {},
      queryParams: {
        pageIndex: 1,
        pageSize: 5,
        name: undefined
      },
      tpls: [],
      newTpls: [],
      ruleForm: {
        workOrderId: 0,
        title: '',
        projectNo: '',
        process: '',
        classify: '',
        state: [],
        source: '',
        source_state: '',
        process_method: '',
        tpls: {
          form_structure: [],
          form_data: []
        },
        newTpls: {},
        tasks: [],
        status: 0
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      },
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        }
      }
    }
  },
  computed: {
    ...mapGetters(['name']),
    orderState() {
      if (this.workOrdeInfo.id != null) {
        if (this.workOrdeInfo.status == 1) {
          return '未提交(草稿)'
        } else {
          return `${this.workOrdeInfo.current_state_name}【${this.workOrdeInfo.principals
          }】`
        }
      } else {
        return '未提交'
      }
    }
  },
  methods: {
    handlePrint(params) {
      printJS({
        maxWidth: 1920,
        documentTitle: '甘肃省人民医院医务一网通办',
        printable: params.printable, // 'printFrom',
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })
    },
    handleClose(val) {
      this.dialogVisible = false
      this.$refs['ruleForm'].resetFields()
    },
    open() {
      this.resetDialog()
      this.dialogVisible = true
      this.getProcessNodeList()
    },
    resetDialog() {
      Object.assign(this.$data, this.$options.data())
    },
    handleLeader() {
      this.$refs.leaderRef.handleInversion()
    },
    getProcessNodeList() {
      processStructure({
        processId: 3
      }).then(response => {
        this.processStructureValue = response.data
        this.currentNode = this.processStructureValue.nodes[0]
        this.processStructureValue.tpls[0].form_structure.list[1].options.disabled = true
      })
    },
    draftAction(item) {
      this.draftDisabled = true
      var stateMap = {}
      this.ruleForm.process = 3
      this.ruleForm.status = 1
      this.ruleForm.classify = this.processStructureValue.process.classify
      stateMap['id'] = item.target
      this.ruleForm.source_state = this.processStructureValue.nodes[
        this.active
      ].label

      for (var v of this.processStructureValue.nodes) {
        if (v.id === item.target) {
          if (v.assignType !== undefined) {
            stateMap['process_method'] = v.assignType
          }
          if (v.assignValue !== undefined) {
            stateMap['processor'] = Array.from(new Set(v.assignValue))
          }
          stateMap['label'] = v.label
          stateMap['desc'] = v.desc
          break
        }
      }
      this.ruleForm.state = [stateMap]

      this.ruleForm.tpls = {
        form_name: [],
        form_structure: [],
        form_data: []
      }

      var promiseList = []

      this.tpls = []
      for (var tpl of this.newTpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id
        })
      }

      for (var tpl of this.processStructureValue.tpls) {
        tpl.form_structure.id = tpl.id
        this.ruleForm.tpls.form_structure.push(tpl.form_structure)
        this.ruleForm.tpls.form_name.push(tpl.name)
        promiseList.push(
          this.$refs['generateForm-' + tpl.id][0].getDataNoValidate()
        )
      }

      Promise.all(promiseList)
        .then(values => {
          this.ruleForm.source = this.processStructureValue.nodes[
            this.active
          ].id
          console.log(values)
          for (var item of values) {
            if (item.hasOwnProperty('project_name')) {
              this.ruleForm.title = item.project_name
            }
          }
          if (this.tpls.length > 0) {
            for (var tplDataIndex in this.tpls) {
              this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
            }
            this.ruleForm.newTpls = this.tpls
          }

          this.ruleForm.tpls.form_data = values
          this.ruleForm.is_exec_task = item.isExecuteTask
          draftWorkOrder(this.ruleForm)
            .then(response => {
              if (response.code === 200) {
                console.log(response)
                this.$message({
                  type: 'success',
                  message: '暂存成功!'
                })
                this.workOrdeInfo = response.data.workOrder
                this.ruleForm.workOrderId = this.workOrdeInfo.id
                this.newTpls = response.data.tpls
                this.draftDisabled = false
                this.recallStatus = 0
                console.log(this.ruleForm)
              }
            })
            .catch(() => {
              this.draftDisabled = false
            })
        })
        .catch(() => {
          this.draftDisabled = false
        })
    },

    selectLeader(userId) {
      this.ruleForm.state[0]['processor'] = [userId]
      if (this.ruleForm.workOrderId > 0) {
        updateWorkOrder(this.ruleForm)
          .then(response => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '提交成功!'
              })
              this.workOrdeInfo = response.data.workOrder
              this.ruleForm.workOrderId = this.workOrdeInfo.id
              this.recallStatus = 0
              this.$router.push({ path: '/project/applyList' })
              // this.$router.push({ path: "/process/upcoming" });
            }
          })
          .catch(() => {
            this.submitDisabled = false
          })
      } else {
        createWorkOrder(this.ruleForm)
          .then(response => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '提交成功!'
              })
              this.workOrdeInfo = response.data.workOrder
              this.ruleForm.workOrderId = this.workOrdeInfo.id
              this.recallStatus = 0
              this.$router.push({ path: '/project/applyList' })
              // this.$router.push({ path: "/process/upcoming" });
            }
          })
          .catch(() => {
            this.submitDisabled = false
          })
      }
    },
    recallOrder() {
      this.recallDisabled = true
      const recallParams = {
        work_oroder_id: this.workOrdeInfo.id,
        process_id: this.workOrdeInfo.process
      }
      recallWorkOrder(recallParams)
        .then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '撤回成功!'
            })
            this.workOrdeInfo = response.data.workOrder
            this.ruleForm.workOrderId = this.workOrdeInfo.id
            this.recallDisabled = false
            this.recallStatus = 1
            // this.$router.push({ path: "/process/upcoming" });
          }
        })
        .catch(() => {
          this.recallDisabled = false
        })
    },
    submitAction(item) {
      console.log(item)
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.submitDisabled = true
          var stateMap = {}
          this.ruleForm.process = 3
          this.ruleForm.status = 0
          this.ruleForm.classify = this.processStructureValue.process.classify
          stateMap['id'] = item.target
          this.ruleForm.source_state = this.processStructureValue.nodes[
            this.active
          ].label
          for (var v of this.processStructureValue.nodes) {
            if (v.id === item.target) {
              if (v.assignType !== undefined) {
                stateMap['process_method'] = v.assignType
              }
              if (v.assignValue !== undefined) {
                stateMap['processor'] = Array.from(new Set(v.assignValue))
              }
              stateMap['label'] = v.label
              stateMap['desc'] = v.desc
              break
            }
          }
          this.ruleForm.state = [stateMap]

          this.ruleForm.tpls = {
            form_name: [],
            form_structure: [],
            form_data: []
          }

          var promiseList = []

          this.tpls = []
          for (var tpl of this.newTpls) {
            this.tpls.push({
              tplDataId: tpl.id,
              tplId: tpl.form_structure.id
            })
          }

          for (var tpl of this.processStructureValue.tpls) {
            tpl.form_structure.id = tpl.id
            this.ruleForm.tpls.form_structure.push(tpl.form_structure)
            this.ruleForm.tpls.form_name.push(tpl.name)
            promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
          }
          Promise.all(promiseList)
            .then(values => {
              this.ruleForm.source = this.processStructureValue.nodes[
                this.active
              ].id
              // console.log(values);
              let leadId = 0
              for (var item of values) {
                if (item.hasOwnProperty('project_name')) {
                  this.ruleForm.title = item.project_name
                }
                if (item.hasOwnProperty('leader_name')) {
                  leadId = item.leader_name
                }
              }
              if (this.tpls.length > 0) {
                for (var tplDataIndex in this.tpls) {
                  this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
                }
                this.ruleForm.newTpls = this.tpls
              }
              this.ruleForm.tpls.form_data = values
              this.ruleForm.is_exec_task = item.isExecuteTask

              // this.handleLeader();
              this.selectLeader(leadId)
              this.submitDisabled = false
            })
            .catch(() => {
              this.submitDisabled = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
  display: none !important;
}

::v-deep .el-table .disabledCheck .cell::before {
  content: "请选择";
  text-align: center;
  line-height: 37px;
}

.baqsj-container {
  max-width: 1530px;
  // background: #ebf4fa;
  border-radius: 12px;

  .apply-box {
    border-radius: 15px;
    .line {
      height: 22px;
      width: 5px;
      background: #277fd6;
    }
  }
}
</style>
